async function GuessZprj(uri) {
  let ret = await getZprjJson(uri);
  if (ret != false) {
    return ret;
  }

  ret = await getZprj(uri);
  if (ret != false) {
    return ret;
  }

  ret = await getTilesetZprj(uri);
  if (ret != false) {
    return ret;
  }

  return false;
}

async function getZprjJson(uri) {
  try {
    let zprj_uri = uri.substring(0, uri.length - 5) + "_zprj.json";
    let data = await fetch(zprj_uri);
    if (data.status != 200) {
      return false;
    }
    let dataJson = await data.json();
    return dataJson;
  }
  catch (e) {
    return false;
  }
}

async function getZprj(uri) {
  try {
    let zprj_uri = uri.substring(0, uri.length - 5) + ".zprj";
    let data = await fetch(zprj_uri);
    if (data.status != 200) {
      return false;
    }
    let dataJson = await data.json();
    return dataJson;
  }
  catch (e) {
    return false;
  }
}

function isNotZero(data) {
  return Math.abs(Number(data)) < 0.0001;
}

async function getTilesetZprj(uri) {
  try {
    let data = await fetch(uri);
    if (data.status != 200) {
      return false;
    }
    let dataJson = await data.json();
    let arrTransform = dataJson?.root?.transform;
    if (Array.isArray(arrTransform) && arrTransform.length == 16) {
      let transX = Number(arrTransform[12]);
      let transY = Number(arrTransform[13]);
      if (isNotZero(transX) && isNotZero(transY)) {
        return {
          zprj: {
            way: "manual",
            x: transX,
            y: transY
          }
        }
      }
    }

    let box = dataJson?.root?.boundingVolume?.box;
    if (Array.isArray(arrTransform)) {
      let transX = Number(box[0]);
      let transY = Number(box[1]);
      if (isNotZero(transX) && isNotZero(transY)) {
        return {
          zprj: {
            way: "manual",
            x: transX,
            y: transY
          }
        }
      }
    }
  }
  catch (e) {
    return false;
  }

  return false;
}

export {
  GuessZprj
}